package com.code.coinprice.handlers.route;

import com.code.coinprice.models.CoinPriceSource;
import com.code.coinprice.models.RelativeCoinPrice;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.enums.ReadyState;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public abstract class CoinPriceInvokeHandler {

    protected CoinPriceInvokeHandler coinPriceInvokeHandler;

    public void setCoinPriceInvokeHandler(CoinPriceInvokeHandler coinPriceInvokeHandler) {
        this.coinPriceInvokeHandler = coinPriceInvokeHandler;
    }

    abstract public List<RelativeCoinPrice> getCoinPriceList(CoinPriceSource coinPriceSource);

    abstract public String getCoinPrice(String source, String coinType);

    /**
     * 获取客户端连接实例
     */
    public void sendWebSocket(WebSocketClient webSocketClient, String platform, String msg) {

        //请求与服务端建立连接
        webSocketClient.connect();

        Timer t = new Timer();
        t.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                if (webSocketClient.isClosed()) {
                    // log.error("{}币价平台对应的客户端断线重连", platform);
                    webSocketClient.reconnect();
                    while (!webSocketClient.getReadyState().equals(ReadyState.OPEN)) {
                        // log.info("{}币价平台对应的客户端进行断开重新连接中···请稍后", platform);
                    }
                    webSocketClient.send(msg);
                }
            }
        }, 1000, 5000);

        // 解决org.java_websocket.exceptions.WebsocketNotConnectedException这种异常
        // 参考： https://blog.csdn.net/down___load/article/details/107417751
        while (!webSocketClient.getReadyState().equals(ReadyState.OPEN)) {
            // log.info("{}币价平台对应的客户端连接中···请稍后", platform);
        }
        webSocketClient.send(msg);
    }
}
